package com.baixun.gassystem.service.impl;

import com.baixun.gasentity.entity.SysDepartmentPermissions;
import com.baixun.gasentity.entity.SysDepartmentRoles;
import com.baixun.gassystem.mapper.SysDepartmentPermissionMapper;
import com.baixun.gassystem.mapper.SysDepartmentRolesMapper;
import com.baixun.gassystem.service.SysDepartmentRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: 上海燃气驾驶舱
 * @description: 角色权限实现类
 * @author: yesong
 **/
@Service
public class SysDepartmentRoleServiceImpl extends ServiceImpl<SysDepartmentRolesMapper, SysDepartmentRoles> implements SysDepartmentRoleService {
    @Autowired
    private SysDepartmentRolesMapper rolesMapper;
    @Autowired
    private SysDepartmentPermissionMapper permissionsMapper;

    @Override
    public List<SysDepartmentRoles> getAllRoles() {
        return rolesMapper.selectList(null); // 查询所有角色
    }

    @Override
    public SysDepartmentRoles getRoleByName(String name) {
        QueryWrapper<SysDepartmentRoles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_name", name);
        return rolesMapper.selectOne(queryWrapper); // 按角色名查询
    }

    @Override
    public void createRole(SysDepartmentRoles role) {
        rolesMapper.insert(role); // 插入新角色
    }

    @Override
    public void updateRole(SysDepartmentRoles role) {
        rolesMapper.updateById(role); // 更新角色信息
    }

    @Override
    public void deleteRole(Long id) {
        rolesMapper.deleteById(id); // 逻辑删除角色
    }

    /**
     * 为指定角色分配权限
     * @param roleId
     * @param permissionIds
     */
    @Override
    public void assignPermissions(Long roleId, List<Long> permissionIds) {
            // 检查角色是否存在
            SysDepartmentRoles role = rolesMapper.selectById(roleId);
            if (role == null) {
                throw new RuntimeException("角色不存在");
            }
            // 检查每个权限是否有效
            for (Long permissionId : permissionIds) {
                if (permissionsMapper.selectById(permissionId) == null) {
                    throw new RuntimeException("权限ID " + permissionId + " 不存在");
                }
            }
            for (Long permissionId : permissionIds) {
                // 为角色分配权限
                rolesMapper.insertRolePermission(roleId, permissionId);
            }
        }
    }
